<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-01-15
 * @Time: 15:26
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： UserSubscribeSpecial.php
 */
namespace app\api\model\special;

use app\common\model\BuyBill;
use app\common\model\Sales;
use think\Db;
use think\db\Query;
use think\Log;
use think\Model;

class UserSubscribeSpecial extends Model {
    protected $table = 'user_subscribe_special';
    protected $pk = 'ust_id';

    /**
     * isBuy
     * 查询当前登录用户是否购买（订阅）专栏
     * 及已订阅专栏的时效状态
     *
     * @author zhengkai
     * @date 2018-01-15
     *
     * @param int $uid 用户id
     * @param int $scid 专栏栏目id
     * @return int
     */
    public static function isBuy($uid, $scid)
    {
        $data = self::where('ust_user', $uid)
            ->where('ust_special', $scid)
            ->field('ust_expiry_date')
            ->find();

        if ($data) {
            if (time() > $data['ust_expiry_date']) {
                if (self::checkInCourseService($uid, $scid)) {
                    return 1;
                }
                return 2; // 已购买，已过期
            }
            return 1; // 已购买
        } else {
            if (self::checkInCourseService($uid, $scid)) {
                return 1;
            }
            return 0; // 未购买
        }
    }

    /**
     * 判断绑定的课程已购买
     *
     * @param $uid
     * @param $cid
     * @return bool
     */
    public static function checkInCourseService($uid, $cid)
    {
        $sql = <<<SQL
SELECT exists(
  SELECT 1 FROM user_buy_curriculum ubc 
  JOIN course_bind_service cbs ON cbs.curriculum_id=ubc.uc_curriculum
  WHERE ubc.uc_user=:uid AND cbs.bind_column_id=:scid
) e
SQL;
        $re = Db::query($sql, ['uid' => $uid, 'scid' => $cid]);
        return $re[0]['e'] ?? false;
    }

    /**
     * totalSubscribe
     * 统计单个专栏的被订阅（购买）总数
     *
     * @author zhengkai
     * @date 2018-01-15
     *
     * @param $scid
     * @return int|string
     */
    public static function totalSubscribe($scid)
    {
        $data = self::where('ust_special', $scid)->count('ust_id');

        return $data;
    }

    /**
     * getBuyInfo
     * 用于支付的方法，计算商品总价格、获取商品信息等
     *
     * @author jjj
     * @update zhengkai 20180117
     *
     * @param $uid
     * @param $column_id
     * @return array|bool
     */
    public static function getBuyInfo($uid, $column_id) {
        // 查询出购买的专栏数据
        $column = SpecialColumn::get($column_id);

        if (empty($column)) return false;

        $price = $price_orig = $column['column_price'];
        $detail = "价格￥{$price}。";
        $result = [
            'price_orig' => $price, // 原价
            'price' => $price_orig, // 优惠价格
            'title' => "专栏《{$column['column_title']}》",
            'detail' => '',
            'apple_pay_price' => $column['apple_pay_price'],
            'apple_pay_production_id' => $column['apple_pay_production_id'],
        ];

        // TODO 优惠活动
        if ($column['column_sales'] > 0) {
            $sales = Sales::get($column['column_sales']);
            if ($sales && $sales->isAvailable()) {
                $re = $sales->finalPrice($price, $detail);
                $result['price'] = $re['price'];
                $result['detail'] = $re['detail'];
                $result['gifts'] = $re['gifts'];
            }
        }

        return $result;
    }

    /**
     * 检查专栏是否订阅
     * checkBought
     *
     * @author jjj
     * @update zhengkai 2018-01-17
     *
     * @param $uid
     * @param $column_id
     * @return bool|mixed
     */
    public static function checkBought($uid, $column_id) {
        $data = self::get(function (Query $query) use (&$uid, &$column_id) {
            $query->where('ust_user', $uid)
                ->where('ust_special', $column_id);
        });

        if ($data && ($data['ust_expiry_date']>time())) {
            return true;
        } else {
            return false;
        }
    }

    public static function getSimpleList($ids) {
        return SpecialColumn::whereIn('column_id',$ids)->field('column_id, column_title')->select();
    }

    /**
     * countDay
     * 计算用户订阅专栏剩余有效天数
     *
     * @author zhengkai
     * @date 2018-02-23
     *
     * @param int $uid 用户id
     * @param int $column_id 专栏id
     * @return int
     */
    public static function countDay($uid, $column_id)
    {
        $data = self::get(function ($query) use (&$uid, &$column_id) {
            $query->where('ust_user', $uid)
                ->where('ust_special', $column_id);
        });

        if ($data) {
            // 订阅到期天数计算
            $now = time();
            $expiryTime = date_create(date('Y-m-d', $data['ust_expiry_date']));
            $currTime = date_create(date('Y-m-d', $now));
            $expiryDay = date_diff($expiryTime, $currTime);

            return ($now>=$data['ust_expiry_date'])?0:((int)$expiryDay->format('%a')-1); // 需要减去一天，因为到期时间是到期日期的第二天的零点
        } else {
            return 0;
        }
    }

    /**
     * createOrder
     * 创建订阅订单记录
     *
     * @author zhengkai
     * @date 2018-01-17
     *
     * @param array $param
     * @return bool
     */
    private static function createOrder($param=[])
    {
        // 传入参数检测
        $param_list = ['uss_id', 'bill_id', 'remark'];
        foreach ($param as $key=>$val){
            if (!in_array($key, $param_list)) {
                Log::error('创建订阅订单记录错误信息：参数不正确');
                return false;
            }
        }

        Db::table('user_subscribe_order')->insert([
            'uss_id' => $param['uss_id'],
            'bill_id' => $param['bill_id'],
            'remark' => $param['remark']
        ]);
    }

    /**
     * afterBought
     * 专栏订阅（购买/付款）后数据处理
     *
     * @author zhengkai
     * @date 2018-01-17
     *
     * @param $bill_id
     * @param $uid
     * @param $column_id
     * @param BuyBill $bill
     * @return bool
     */
    public static function afterBought($bill_id, $uid, $column_id, BuyBill $bill)
    {
        // 查询出购买的专栏数据
        $column = Db::table('special_column')->where('column_id', $column_id)->field('column_id, column_expiry')->find();
        $day = ((int)$column['column_expiry']+1); // 订阅到期时间，订阅有效期+1天

        // 查询用户是否已经订阅（专栏）
        $data = self::get(function ($query) use (&$uid, &$column_id) {
            $query->where('ust_user', $uid)
                ->where('ust_special', $column_id);
        });

        if ($data) {
            // 已经订阅则只对订阅有效期进行更新
            self::where('ust_id', $data['ust_id'])->update([
                'ust_expiry_date' => strtotime("+{$day} day",strtotime(date('Y-m-d',time())))
            ]);

            self::createOrder([
                'uss_id' => $data['ust_id'],
                'bill_id' => $bill_id,
                'remark' => '续订'
            ]);
        } else {
            // 未订阅则创建新的订阅记录
            $result = self::create([
                'ust_user' => $uid,
                'ust_bill' => $bill_id,
                'ust_special' => $column_id,
                'ust_expiry_date' => strtotime("+{$day} day",strtotime(date('Y-m-d',time())))
            ]);

            self::createOrder([
                'uss_id' => $result->ust_id,
                'bill_id' => $bill_id,
                'remark' => '新购（订阅）'
            ]);
        }
    }

    /**
     * getUserSubscribe
     * 获取用户订阅专栏数据
     *
     * @author zhengkai
     * @date 2018-01-17
     * @update v1.3.2 20180223 zhengkai
     *      增加订阅专栏到期天数字段
     *
     * @param int $uid 用户id
     * @return array
     */
    public function getUserSubscribe($uid, $page=1, $limit=10)
    {
        $data = self::all(function ($query) use (&$uid, &$page, &$limit) {
            $query->join('special_column sc', 'ust_special=sc.column_id', 'left')
                ->join('buy_bill b','ust_bill=b.bill_id','left')
                ->field('column_id, column_title, column_description, feed, covers->>\'list\' as column_cover, column_createtime, column_updatetime, ust_expiry_date,column_expiry,b.bill_pay_amount')
                ->where('ust_user', $uid)
                ->page($page, $limit);
        });

        if (empty($data)) return [];

        $result = [];
        foreach ($data as $key=>$val) {
            $val->column_description = stripHtml($val->column_description);

            // 订阅到期天数
            $val->expiry_day = self::countDay($uid, $val->column_id);

            // 栏目更新时间处理
            if (empty($val->column_updatetime)) {
                $val->column_updatetime = tranTime($val->column_createtime);
            } else {
                $val->column_updatetime = tranTime($val->column_updatetime);
            }
            unset($val->column_createtime);

            $val->column_subscribe_status = UserSubscribeSpecial::isBuy($uid, $val->column_id);
            // 专栏自定义订阅数小于实际订阅数时显示实际订阅数
            $val->column_subscribe_total = countDataNum(UserSubscribeSpecial::totalSubscribe($val->column_id), $val->feed, true);

            unset($val['feed']);

            $result[] = $val->toArray();
        }

        return $result;
    }
}